<template>
  <div>
    <div v-loading="loading" class="panel advert-detail-panel">
      <div class="panel-header">{{ $route.meta.title || '' }}</div>
      <i-form
        ref="form"
        class="advert-form"
        :items="formItems"
        :rules="rules"
        :model="form"
      >
        <template v-if="type === 'detail'" slot="img">
          <el-form-item label="广告图片" prop="advertPicId">
            <el-image :src="getImgUrl(form)" />
          </el-form-item>
        </template>
        <template v-if="type !== 'detail'" slot="img">
          <el-form-item label="广告图片" prop="advertPicId">
            <hyc-form-upload
              ref="bl_pic"
              v-model="form.advertPicId"
              :upload-data="stationImgData"
              :uploadTip="imgUploadTip[form.advertType]"
            >
            </hyc-form-upload>
          </el-form-item>
        </template>
        <template v-if="type !== 'detail'" slot="link">
          <el-form-item
            :label="form.jumpType === 'WEB' ? '广告链接' : '小程序路径'"
            prop="advertUrl"
          >
            <div>
              <el-radio-group v-model="form.hasLink">
                <el-radio :label="false">{{
                  form.jumpType === 'WEB' ? '无链接' : '小程序首页'
                }}</el-radio>
                <el-radio :label="true">{{
                  form.jumpType === 'WEB' ? '输入链接' : '输入小程序路径'
                }}</el-radio>
              </el-radio-group>
              <el-input
                maxlength="255"
                clearable
                show-word-limit
                v-model="form.advertUrl"
                v-if="form.hasLink === true"
              />
            </div>
          </el-form-item>
        </template>
        <template slot="advertStart">
          <el-form-item label="开始时间" prop="advertStart" class="is-required">
            <date-picker
              ref="advertStart"
              type="datetime"
              v-model="advertStart"
              format="YYYY-MM-DD HH:mm"
              placeholder="请选择开始时间"
              :disabled-date="disabledActStartDate"
              :time-picker-options="advertStartPicker"
              @change="handleActStartChange"
              @pick="handleActStartPick"
              @clear="handleActStartClear"
              :renderInputText="renderActStartInputText"
            >
            </date-picker>
          </el-form-item>
        </template>
        <template slot="advertEnd">
          <el-form-item label="结束时间" prop="advertEnd" class="is-required">
            <date-picker
              ref="advertEnd"
              type="datetime"
              v-model="advertEnd"
              format="YYYY-MM-DD HH:mm"
              placeholder="请选择结束时间"
              :disabled-date="disabledActEndDate"
              :time-picker-options="advertEndPicker"
              @change="handleActEndChange"
              @pick="handleActEndPick"
              @clear="handleActEndClear"
              :renderInputText="renderActEndInputText"
            ></date-picker>
          </el-form-item>
        </template>
      </i-form>
    </div>
    <div v-loading="tableLoading" v-if="form.advertLevel === 'STAION'">
      <TableSearch
        ref="tableSearch"
        :tableBtns="tableBtns"
        :columns="columns"
        :tableData="tableData"
        :form="tableForm"
        @handleTableData="handleTableData"
      >
        <template slot="tableSearchHeader">
          <div class="advert-detail-table__header">
            <div
              v-if="type !== 'detail'"
              class="advert-detial-table__header__title"
            >
              <span style="color: red">*</span>
              选择电站
            </div>
            <div
              v-if="type !== 'detail'"
              @click="handleClearCheckList"
              class="advert-detial-table__header__button"
            >
              清空选择电站
            </div>
            <div
              v-if="type !== 'detail'"
              @click="handlePreview"
              class="advert-detial-table__header__button"
            >
              预览所选电站
              <span class="dvert-detial-table__header__button_red">{{
                `(已选择电站：${this.checkList.length}个)`
              }}</span>
            </div>
          </div>
          <div v-if="type !== 'detail'" class="search-form">
            <i-form
              :inline="true"
              :default-span="8"
              :items="defaultFormItemsInline"
              :model="tableForm"
              :label-width="20"
            >
              <template slot="address">
                <el-form-item>
                  <HycAddressCascader v-model="tableForm.area" />
                </el-form-item>
              </template>
            </i-form>
            <el-button type="success" @click="handleQuery">查询</el-button>
            <el-button type="warning" @click="reset">重置</el-button>
            <el-button type="primary" @click="handleCheckAll"
              >结果全选</el-button
            >
          </div>
        </template>
        <el-table-column
          v-if="type !== 'detail'"
          slot="checkbox"
          label="选择电站"
        >
          <template #default="{ row }">
            <el-checkbox
              :key="row.id + resetKey"
              @change="
                (val) => {
                  handleCheckChange(val, row)
                }
              "
              :checked="checkList.includes(row.id)"
            />
          </template>
        </el-table-column>
      </TableSearch>
    </div>
    <div v-if="form.advertLevel === 'AREA'" class="panel tag-panel">
      <SelectTree
        :closable="type === 'detail' ? false : true"
        :addAreaBtnDisplay="type === 'detail' ? false : true"
        :checkedData="checkedRegions"
        @listenCheckedData="bindListenCheckedData"
      >
      </SelectTree>
    </div>
    <div class="advert-detail-submit">
      <el-button
        v-if="type !== 'detail'"
        @click="
          () => {
            handleSubmit()
          }
        "
        type="success"
        >确认</el-button
      >
      <el-button type="primary" @click="handleBack">返回</el-button>
    </div>
    <PreviewStationDlg
      :visible.sync="previewVisible"
      :check-list="checkList"
      :key="resetPreview"
    />
  </div>
</template>
<script>
import TableSearch from '@/components/TableSearch'
import SelectTree from '@/components/SelectTree'
import formValidate from '@/utils/validate'
import formatter, { typeMap } from '@/utils/format'
import HycFormUpload from '@/components/hycFormUpload'
import HycAddressCascader from '@/components/hycAddressCascader'
import {
  selectDetail,
  getStationInAdvert,
  updateAdvert,
  insertAdvert,
} from '@/api/activity'
import PreviewStationDlg from './components/PreviewStationDlg'
import DatePicker from 'vue2-datepicker'
import 'vue2-datepicker/index.css'
import 'vue2-datepicker/locale/zh-cn'
import dayjs from 'dayjs'
export default {
  name: 'advertDetail',
  components: {
    TableSearch,
    HycFormUpload,
    HycAddressCascader,
    PreviewStationDlg,
    DatePicker,
    SelectTree,
  },
  mounted() {
    // 必须要先设置formitem，才能给form填数据
    const paths = this.$route.path.split('/')
    if (paths[2] && paths[2] === 'advertDetail') {
      this.type = 'detail'
      this.formItems = this.detailFormItems
    } else {
      this.type = 'edit'
      this.formItems = this.editableFormItems
      this.initFormRules()
    }
    if (this.$route.params.advertId) {
      this.loading = true
      selectDetail({
        id: this.$route.params.advertId,
      })
        .then((res) => {
          let form = {
            advertName: res.advertName,
            advertType: res.advertType,
            advertFrequency: res.advertFrequency,
            advertWeight: res.advertWeight,
            advertPicId: res.advertPicId,
            jumpType: res.jumpType,
            hasLink: res.advertUrl ? true : false,
            advertUrl: res.advertUrl,
            appId: res.appId,
            advertStart: res.advertStart,
            advertEnd: res.advertEnd,
            advertLevel: res.advertLevel,
          }

          this.form = {
            ...form,
          }

          if (res.advertLevel === 'STAION') {
            this.checkList = res.stations.map((item) => item.id)
          } else {
            this.checkedRegions = res.asRelVoList.map((item) => {
              item.id = item.district || item.city || item.province
              item.idPath =
                item.province +
                (item.city ? ',' + item.city : '') +
                (item.district ? ',' + item.district : '')
              item.name =
                item.districtName || item.cityName || item.provinceName
              item.namePath =
                item.provinceName +
                (item.cityName ? '-' + item.cityName : '') +
                (item.districtName ? '-' + item.districtName : '')
              return item
            })
          }
        })

        .finally(() => {
          this.loading = false
          if (this.form.advertLevel === 'STAION') {
            this.$refs.tableSearch.refreshTable()
            this.resetKey += 1
          }
        })
    } else {
      this.type = 'add'
      this.formItems = this.editableFormItems
      this.initFormRules()
      this.$refs.tableSearch.refreshTable()
    }
  },
  data() {
    return {
      resetKey: 1,
      downloadUrl: '/file-management/file/download',
      resetPreview: 1,
      previewVisible: false,
      stationImgData: { fileType: 'IMAGE' },
      loading: false,
      tableLoading: true,
      type: 'detail',
      checkList: [],
      checkedRegions: [],
      selectAllResultForm: {},
      detailFormItems: [
        {
          label: '广告名称',
          type: 'detail',
          value: 'advertName',
        },
        {
          label: '广告类型',
          value: 'advertType',
          type: 'detail',
          options: typeMap.radioOptions([], 'advertType'),
          formatter: (val) => {
            return typeMap.advertType[this.form[val]]
          },
        },
        {
          label: '广告权重',
          value: 'advertWeight',
          type: 'detail',
          ifRender: () => {
            return this.form.advertType === 'BANNERPIC'
          },
        },
        {
          label: '广告频次',
          value: 'advertFrequency',
          type: 'detail',
          formatter: (val) => {
            return typeMap.advertFrequency[this.form[val]]
          },
          ifRender: () => {
            return this.form.advertType === 'SCREENPIC'
          },
        },
        {
          slot: 'img',
        },
        {
          label: '跳转类型',
          value: 'jumpType',
          type: 'detail',
          formatter: (val) => {
            return typeMap.advertJumpType[this.form[val]]
          },
        },
        {
          label: '广告链接',
          value: 'advertUrl',
          type: 'detail',
          formatter: (val) => {
            return this.form[val] ? this.form[val] : '/'
          },
          ifRender: () => {
            return this.form.jumpType === 'WEB'
          },
        },
        {
          label: '小程序路径',
          value: 'advertUrl',
          type: 'detail',
          formatter: (val) => {
            return this.form[val] ? this.form[val] : '小程序首页'
          },
          ifRender: () => {
            return this.form.jumpType === 'WEIXINMINI'
          },
        },
        {
          label: 'Appid',
          type: 'detail',
          value: 'appId',
          ifRender: () => {
            return this.form.jumpType === 'WEIXINMINI'
          },
        },

        {
          label: '广告时间',
          type: 'detail',
          formatter: () => {
            return (
              typeMap.formatTime(this.form.advertStart) +
              '  ——  ' +
              typeMap.formatTime(this.form.advertEnd)
            )
          },
        },
      ],
      editableFormItems: [
        {
          label: '广告名称',
          type: 'text',
          value: 'advertName',
          maxlength: 16,
          'show-word-limit': true,
          clearable: true,
        },
        {
          label: '广告类型',
          value: 'advertType',
          type: 'radio',
          options: typeMap.radioOptions([], 'advertType'),
        },
        {
          label: '广告权重',
          value: 'advertWeight',
          type: 'select',
          options: [1, 2, 3, 4, 5, 6].map((item) => ({
            label: item,
            value: item,
          })),
          ifRender: () => {
            return this.form.advertType === 'BANNERPIC'
          },
        },
        {
          label: '广告频次',
          value: 'advertFrequency',
          type: 'select',
          options: typeMap.selectOptions([], 'advertFrequency'),
          ifRender: () => {
            return this.form.advertType === 'SCREENPIC'
          },
        },
        {
          slot: 'img',
        },
        {
          label: '跳转类型',
          value: 'jumpType',
          type: 'radio',
          options: typeMap.radioOptions([], 'advertJumpType'),
          change: () => {
            this.form.hasLink = false
          },
        },
        {
          slot: 'link',
        },
        {
          label: 'Appid',
          type: 'text',
          value: 'appId',
          maxlength: 50,
          'show-word-limit': true,
          clearable: true,
          ifRender: () => {
            return this.form.jumpType === 'WEIXINMINI'
          },
        },
        {
          slot: 'advertStart',
        },
        {
          slot: 'advertEnd',
        },
        {
          label: '广告范围',
          value: 'advertLevel',
          type: 'radio',
          options: typeMap.radioOptions([], 'advertLevel'),
        },
      ],
      formItems: [],
      rules: {},
      form: {
        advertType: 'SCREENPIC',
        jumpType: 'WEB',
        hasLink: false,
        advertLevel: 'STAION',
      },
      area: {},
      columns: [
        {
          slot: 'checkbox',
        },
        {
          label: '创建日期',
          prop: 'createTime',
          formatter,
        },
        {
          label: '所在地区',
          prop: 'province',
        },
        {
          label: '充电站名',
          prop: 'stationName',
        },
        {
          label: '地址描述',
          prop: 'stationAddress',
        },
        {
          label: '包含端口',
          prop: 'portNum',
        },
        {
          label: '所属代理商',
          prop: 'systemUserName',
        },
      ],
      tableBtns: [],
      tableForm: {},
      defaultFormItemsInline: [
        {
          slot: 'address',
        },
        {
          placeholder: '请输入电站名',
          type: 'text',
          clearable: true,
          value: 'stationName',
        },
        {
          placeholder: '请输入代理商',
          type: 'text',
          clearable: true,
          value: 'mchName',
        },
      ],
      formItemsInline: [],
      tableData: {},
      imgUploadTip: {
        SCREENPIC: '建议图片尺寸：342px*1021px',
        BANNERPIC: '建议图片尺寸：1023px*342px',
      },
      advertStart: '',
      advertEnd: '',
      advertStartPicker: {
        start: '00:00',
        step: '00:05',
        end: '23:55',
      },
      advertEndPicker: {
        start: '00:00',
        step: '00:05',
        end: '23:55',
      },
    }
  },
  watch: {
    'form.hasLink': {
      handler(val) {
        if (this.type === 'detail') return
        if (val === true) {
          this.$set(this.rules, 'advertUrl', [
            {
              required: true,
              message:
                this.form.jumpType === 'WEB'
                  ? '请输入链接'
                  : '请输入小程序路径',
            },
            {
              validator:
                this.form.jumpType === 'WEB'
                  ? formValidate('validateUrl')
                  : formValidate('validateMiniUrl'),
            },
          ])
          this.$nextTick(() => {
            if (!this.$refs.form) return
            this.$refs.form.$refs.form.clearValidate('advertUrl')
          })
        } else {
          this.$set(this.rules, 'advertUrl', [])
          delete this.form.advertUrl

          this.$nextTick(() => {
            if (!this.$refs.form) return
            this.$refs.form.$refs.form.clearValidate('advertUrl')
          })
        }
      },
      // immediate: true
    },
    'form.advertStart': {
      handler(val, oldVal) {
        if (val !== oldVal) {
          this.$refs.form && this.$refs.form.validateField('advertStart')
        }
      },
    },
    'form.advertEnd': {
      handler(val, oldVal) {
        if (val !== oldVal) {
          this.$refs.form && this.$refs.form.validateField('advertEnd')
        }
      },
    },
  },
  methods: {
    disabledActStartDate(date) {
      return (
        date < new Date().setHours(0, 0, 0, 0) ||
        date > new Date(this.form.advertEnd).setHours(0, 0, 0, 0)
      )
    },
    disabledActEndDate(date) {
      return (
        date < new Date(this.form.advertStart).setHours(0, 0, 0, 0) ||
        date < new Date().setHours(0, 0, 0, 0)
      )
    },
    handleActStartChange(val, type) {
      this.actStartateType = type
    },
    handleActStartPick(date) {
      let flag = date > new Date()
      this.advertStartPicker.start = flag
        ? '00:00'
        : new Date().getHours() +
          ':' +
          Math.ceil(new Date().getMinutes() / 5) * 5
      if (this.form.advertEnd) {
        if (date < new Date(this.form.advertEnd).setHours(0, 0, 0, 0)) {
          this.advertStartPicker.end = '23:55'
        } else {
          date = new Date(
            new Date(this.form.advertEnd).setMinutes(
              new Date(this.form.advertEnd).getMinutes() - 5
            )
          )
          this.advertStartPicker.end = date.getHours() + ':' + date.getMinutes()
        }
      }
    },
    handleActStartClear() {
      this.form.advertStart = ''
    },
    renderActStartInputText(val) {
      if (this.actStartateType === 'time') {
        this.form.advertStart = Date.parse(val)
        return dayjs(this.form.advertStart).format('YYYY-MM-DD HH:mm')
      } else {
        this.form.advertStart = this.form.advertStart
          ? dayjs(this.form.advertStart).valueOf()
          : undefined
        return this.form.advertStart
          ? dayjs(this.form.advertStart).format('YYYY-MM-DD HH:mm')
          : undefined
      }
    },
    renderActEndInputText(val) {
      if (this.actEndDateType === 'time') {
        this.form.advertEnd = Date.parse(val)
        return dayjs(this.form.advertEnd).format('YYYY-MM-DD HH:mm')
      } else {
        this.form.advertEnd = this.form.advertEnd
          ? dayjs(this.form.advertEnd).valueOf()
          : undefined
        return this.form.advertEnd
          ? dayjs(this.form.advertEnd).format('YYYY-MM-DD HH:mm')
          : undefined
      }
    },
    handleActEndChange(val, type) {
      this.actEndDateType = type
    },
    handleActEndPick(date) {
      if (!this.form.advertStart) {
        this.advertEndPicker.start =
          date > new Date()
            ? '00:00'
            : new Date().getHours() +
              ':' +
              Math.ceil(new Date().getMinutes() / 5) * 5
      } else {
        if (date > new Date(this.form.advertStart)) {
          this.advertEndPicker.start = '00:00'
        } else {
          date = new Date(
            new Date(this.form.advertStart).setMinutes(
              new Date(this.form.advertStart).getMinutes() + 5
            )
          )
          this.advertEndPicker.start = date.getHours() + ':' + date.getMinutes()
        }
      }
    },
    handleActEndClear() {
      this.form.advertEnd = ''
    },
    itemChecked(row) {
      return this.checkList.includes(row.id)
    },
    handleBack() {
      this.$router.push('/activity/advertList')
    },
    recurrence(totalAmount, currentPage, pageSize) {
      getStationInAdvert({
        ...this.selectAllResultForm,
        pageSize,
        currentPage,
      })
        .then((res) => {
          if (!Array.isArray(res.list)) throw Error('no valid res.list')

          res.list.forEach((item) => {
            this.checkList.push(item.id)
          })

          if (currentPage * pageSize < totalAmount + pageSize) {
            this.recurrence(totalAmount, currentPage + 1, pageSize)
          } else {
            this.tableLoading = false
            this.resetKey += 1
          }
        })
        .catch((err) => {
          console.log(err)
          this.tableLoading = false
        })
    },
    handleCheckAll() {
      this.tableLoading = true
      getStationInAdvert({
        ...this.selectAllResultForm,
        pageSize: 50,
        currentPage: 1,
      })
        .then((res) => {
          if (!res.totalAmount) throw Error('no totalAmount')
          this.checkList = []

          this.recurrence(res.totalAmount, 1, 50)
        })
        .catch((err) => {
          console.log(err)
        })
    },
    handlePreview() {
      if (this.checkList.length <= 0) {
        this.$message({
          type: 'warning',
          showClose: true,
          message: '选择电站之后才可预览！',
        })
        return
      }
      this.previewVisible = true
      this.resetPreview += 1
    },
    handleClearCheckList() {
      this.checkList = []
      this.resetKey += 1
    },
    initFormRules() {
      this.rules = {
        advertName: [
          { required: true, message: '请输入广告名称' },
          { validator: formValidate('validateAdministrator') },
        ],
        advertType: [{ required: true }],
        advertFrequency: [{ required: true, message: '请选择广告频次' }],
        advertWeight: [{ required: true, message: '请选择广告权重' }],
        advertPicId: [{ required: true, message: '请上传图片' }],
        jumpType: [{ required: true }],
        appId: [{ required: true, message: '请输入小程序Appid' }],
        advertStart: [
          {
            validator: (rule, value, callback) => {
              if (!this.form.advertStart) {
                return callback(new Error('该项为必填项'))
              } else {
                return callback()
              }
            },
            trigger: ['change', 'blur'],
          },
        ],
        advertEnd: [
          {
            validator: (rule, value, callback) => {
              if (!this.form.advertEnd) {
                return callback(new Error('该项为必填项'))
              } else {
                return callback()
              }
            },
            trigger: ['change', 'blur'],
          },
        ],
      }
    },
    handleHttpActions() {
      this.loading = true
      let qsParams = {
        ...this.form,
      }

      if (!qsParams.hasLink) {
        delete qsParams.advertUrl
      }

      delete qsParams.hasLink

      if (this.form.advertLevel === 'STAION') {
        qsParams.stationIds = this.checkList
      } else {
        qsParams.areaList = this.checkedRegions.map((item) => {
          let idPathArr = item.idPath.split(',')
          let areaObj = { province: idPathArr[0] }
          idPathArr.length > 1 ? (areaObj.city = idPathArr[1]) : null
          idPathArr.length > 2 ? (areaObj.district = idPathArr[1]) : null
          return areaObj
        })
      }

      if (this.type === 'add') {
        insertAdvert(qsParams)
          .then(() => {
            this.$message({
              message: '添加成功！',
              showClose: true,
              type: 'success',
            })

            this.$router.push('/activity/advertList')
          })
          .catch((err) => {
            console.log(err)
          })
          .finally(() => {
            this.loading = false
          })
      } else {
        updateAdvert({
          id: this.$route.params.advertId,
          ...qsParams,
        })
          .then(() => {
            this.$message({
              message: '修改成功！',
              showClose: true,
              type: 'success',
            })

            this.$router.push('/activity/advertList')
          })
          .catch((err) => {
            console.log(err)
          })
          .finally(() => {
            this.loading = false
          })
      }
    },
    handleSubmit() {
      this.$refs.form.validate((valid) => {
        if (!valid) return

        if (
          (this.form.advertLevel === 'STAION' && this.checkList.length === 0) ||
          (this.form.advertLevel === 'AREA' && this.checkedRegions.length === 0)
        ) {
          this.$confirm(
            `请选择参加广告的${
              this.form.advertLevel === 'STAION' ? '电站' : '区域'
            }!`,
            '提示',
            {
              center: true,
              customClass: 'tip-dialog__wrapper',
              showCancelButton: false,
            }
          )
          return
        }

        this.handleHttpActions()
      })
    },
    handleQuery() {
      this.$refs.tableSearch.handleTableData()
    },
    handleCheckChange(val, row) {
      if (val && !this.checkList.includes(row.id)) {
        this.checkList.push(row.id)
      }

      if (!val && this.checkList.includes(row.id)) {
        let index = this.checkList.findIndex((item) => item == row.id)
        this.checkList.splice(index, 1)
      }
    },
    handleTableData(params) {
      if (this.type === 'detail') {
        params.ids = ''

        for (let i = 0; i < this.checkList.length; i++) {
          if (i !== this.checkList.length - 1) {
            params.ids += `${this.checkList[i]},`
          } else {
            params.ids += this.checkList[i]
          }
        }
      }
      if (params.area && params.area.province) {
        params.province = params.area.province
      }

      if (params.area && params.area.city) {
        params.city = params.area.city
      }

      if (params.area && params.area.district) {
        params.district = params.area.district
      }

      delete params.area

      this.tableLoading = true
      getStationInAdvert(params)
        .then((res) => {
          this.tableData = {
            list: res.list,
            totalCount: res.totalAmount,
          }

          this.selectAllResultForm = params
        })
        .catch((err) => {
          console.log(err)
        })
        .finally(() => {
          this.tableLoading = false
        })
    },
    reset() {
      this.tableForm = {
        area: {},
      }
    },
    getImgUrl(row) {
      return (
        process.env.VUE_APP_BASE_URL_API +
        (this.downloadUrl ? this.downloadUrl : '/file/img') +
        '?fileId=' +
        row.advertPicId
      )
    },
    bindListenCheckedData(val) {
      this.checkedRegions = val
    },
  },
}
</script>
<style lang="scss" scoped>
.advert-form {
  padding-right: 300px;
}

.search-form {
  padding-top: 20px;
  display: flex;

  .el-button {
    height: 40px;
    margin-left: 20px;
  }
}

.advert-detail-table__header {
  padding-left: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e8e8e8;
  display: flex;
  flex-wrap: wrap;
}

.advert-detial-table__header__title {
  font-size: 14px;
  font-weight: bold;
  padding-right: 150px;
}

.advert-detial-table__header__button {
  cursor: pointer;
  font-size: 14px;
  color: #4075fe;
  cursor: pointer;
  margin-right: 40px;

  .dvert-detial-table__header__button_red {
    color: red;
  }
}

.tag-panel {
  padding-left: 20px;
}
::v-deep {
  .el-upload__tip {
    color: red;
  }
}
</style>
